﻿using Application.Common.Interfaces;
using MediatR;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel;
using Microsoft.EntityFrameworkCore;
using Common.Attributes;
using Application.Features.Roles.EventHandlers;
using Domain.Entities.Identity;

namespace Application.Features.Roles.Commands.Delete;

#nullable disable

/// <summary>
/// 删除角色
/// </summary>
[Description("删除")]
[GroupDescription(("角色管理"))]
public class DeleteRoleCommand : IRequest<bool>
{
    /// <summary>
    /// 角色唯一标识
    /// </summary>
    [Required(ErrorMessage = "角色唯一标识必填")]
    public List<long> RoleIds { get; set; }
}

/// <summary>
/// 处理程序
/// </summary>
public class DeleteRoleCommandHandler : IRequestHandler<DeleteRoleCommand, bool>
{
    private readonly IApplicationDbContext _context;
    private readonly IMediator _mediator;

    public DeleteRoleCommandHandler(
        IApplicationDbContext context, IMediator mediator)
    {
        _context = context;
        _mediator = mediator;
    }

    /// <summary>
    /// 业务逻辑
    /// </summary>
    /// <param name="request">请求参数</param>
    /// <param name="cancellationToken">取消标记</param>
    /// <returns>返回处理结果</returns>
    public async Task<bool> Handle(DeleteRoleCommand request, CancellationToken cancellationToken)
    {
        var rolesToRemoveRange = await _context.Roles
            .Include(ur=>ur.UserRoles)
               .ThenInclude(u=>u.User)
           .Where(x => request.RoleIds.Contains(x.Id))
           .ToListAsync(cancellationToken);

        _context.Roles.RemoveRange(rolesToRemoveRange);

        await _mediator.Publish(new DeleteRoleEvent<HashSet<User>>(rolesToRemoveRange
            .SelectMany(role => role.UserRoles
            .Select(userRole => userRole.User))
            .ToHashSet()));

        return true;
    }
}
